package com.business_clean.ui.fragment.main;

import static com.business_clean.app.config.Constant.PAGE_SIZE;
import static com.business_clean.app.config.Constant.TYPE_INIT_DATA;
import static com.business_clean.app.config.Constant.TYPE_INIT_LOAD_MORE;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.business_clean.R;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseFragment;
import com.business_clean.app.callback.OnDialogSelectListener;
import com.business_clean.app.config.Constant;
import com.business_clean.app.config.ConstantMMVK;
import com.business_clean.app.ext.CommonUtils;
import com.business_clean.app.uitl.ActivityForwardUtil;
import com.business_clean.app.uitl.CheckListDataUtil;
import com.business_clean.app.uitl.DividerItemDecoration;
import com.business_clean.app.uitl.DownLoadHelper;
import com.business_clean.app.uitl.MMKVHelper;
import com.business_clean.data.initconfig.popup.BaseBottomListEntity;
import com.business_clean.data.mode.BaseDownLoadEntity;
import com.business_clean.data.mode.project.ProjectManager;
import com.business_clean.data.mode.project.ProjectMangerList;
import com.business_clean.data.mode.roster.RosterEntity;
import com.business_clean.data.mode.roster.RosterFilterData;
import com.business_clean.databinding.FragmentRosterBinding;
import com.business_clean.ui.activity.attendance.MyAttendanceActivity;
import com.business_clean.ui.activity.custom.AddCompanyActivity;
import com.business_clean.ui.activity.custom.AddProjectActivity;
import com.business_clean.ui.activity.depart.DepartActivity;
import com.business_clean.ui.activity.personnel.PersonnelDetailActivity;
import com.business_clean.ui.activity.roster.RosterFilterActivity;
import com.business_clean.ui.adapter.roster.RosterAdapter;
import com.business_clean.ui.adapter.roster.RosterRowAdapter;
import com.business_clean.viewmodel.request.RosterViewModel;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.idlefish.flutterboost.FlutterBoost;
import com.idlefish.flutterboost.FlutterBoostRouteOptions;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.schedulers.Schedulers;
import io.reactivex.rxjava3.subjects.PublishSubject;

public class RosterFragment extends BaseFragment<RosterViewModel, FragmentRosterBinding> {

    private RosterAdapter rosterAdapter;
    private RosterRowAdapter rowAdapter;

    private int page = 1;
    private int requestType;

    private String project_uuid = "";

    private String is_head_office = "0";

    private RosterFilterData filterData;

    // 创建一个 PublishSubject 用于监听输入框的文本变化
    private PublishSubject<String> searchSubject = PublishSubject.create();


    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        rosterAdapter = new RosterAdapter();
        getMDatabind().list.recyclerView.setLayoutManager(new LinearLayoutManager(getMActivity()));
        getMDatabind().list.recyclerView.addItemDecoration(new DividerItemDecoration(getMActivity()));
        getMDatabind().list.recyclerView.setAdapter(rosterAdapter);

        rowAdapter = new RosterRowAdapter();
        getMDatabind().recyclerRow.setLayoutManager(new LinearLayoutManager(getMActivity()));
        getMDatabind().recyclerRow.setAdapter(rowAdapter);

        getMDatabind().list.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                requestMore();
            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                requestOne();
            }
        });

        getMDatabind().list.recyclerView.setBackgroundColor(Color.parseColor("#F5F6F9"));

        //1管理员 3人事可以看
        if (Constant.ROLE_MANGER || Constant.ROLE_HR) {
            getMDatabind().ivLeft.setVisibility(View.VISIBLE);
            getMDatabind().ivRightSide.setVisibility(View.VISIBLE);
            //从本地库种获取状态 去设置
            if (MMKVHelper.getBoolean(ConstantMMVK.ROSTER_MENU_STATUS, false)) { //如果默认是 false 那么就默认关闭的
                getMDatabind().recyclerRow.setVisibility(View.VISIBLE);
                getMDatabind().ivLeft.setImageResource(R.mipmap.icon_base_show);
            }
        } else {
            getMDatabind().ivRightSide.setVisibility(View.GONE);
            getMDatabind().ivLeft.setVisibility(View.GONE);
        }

        //如果是保洁人员，也不能去添加人员
        getMDatabind().ivRight.setVisibility(Constant.ROLE_CLEANER ? View.GONE : View.VISIBLE);

        //如果是项目负责人、领班、保洁员 只能看到当前项目下的花名册
        if (Constant.ROLE_PROJECT_OWNER || Constant.ROLE_LEADER || Constant.ROLE_CLEANER && App.appViewModelInstance.getProjectInfo() != null) {
            project_uuid = App.appViewModelInstance.getProjectInfo().getValue().getUuid();
        }
    }

    @Override
    public void lazyLoadData() {
        requestOne();
    }

    @Override
    public void initObserver() {
        //监听创建成员成功
        App.appViewModelInstance.getRefreshMember().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                requestOne();
            }
        });
        //监听总部成员
        App.appViewModelInstance.getRefreshContactManagerList().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                requestOne();
            }
        });

        //监听筛选的回调
        App.appViewModelInstance.getFilterRosterFilterData().observe(this, new Observer<RosterFilterData>() {
            @Override
            public void onChanged(RosterFilterData rosterFilterData) {
                getMDatabind().ivFilter.setImageResource(rosterFilterData.isReset() ? R.mipmap.icon_base_roster_filter : R.mipmap.icon_roster_filter_select);
                if (rosterFilterData.isReset()) {
                    filterData = null;
                } else {
                    filterData = rosterFilterData;
                }
                requestOne();
            }
        });

        //监听输入框的内容
        getMDatabind().etRosterSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                searchSubject.onNext(s.toString());

            }
        });
        // 使用 debounce 操作符实现延迟搜索
        searchSubject
                .debounce(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(query -> {
                    // 在这里执行搜索请求，比如调用网络接口搜索
                    requestOne();
                });
    }

    @Override
    public void onBindViewClick() {
        //进去筛选页面
        getMDatabind().ivFilter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityForwardUtil.startActivity(RosterFilterActivity.class);
            }
        });
        //点击
        rowAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                switch (position) {
                    case 0:
                        project_uuid = "";
                        is_head_office = "0";
                        break;
                    case 1:
                        is_head_office = "1";
                        project_uuid = "";
                        break;
                    default:
                        is_head_office = "2";
                        project_uuid = rowAdapter.getData().get(position).getUuid();
                        break;
                }
                rowAdapter.updateItem(position);
                requestOne();
            }
        });

        rosterAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (view.getId() == R.id.iv_item_roster_call) {
                    PhoneUtils.dial(rosterAdapter.getData().get(position).getMobile());
                }
            }
        });

        rosterAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (Constant.ROLE_CLEANER) {//如果是保洁员，不让点击
                    return;
                }
                Bundle bundle = new Bundle();
                //判断是否外部成员
                if ("1".equals(rosterAdapter.getData().get(position).getIs_out())) {//外部成员直接编辑
                    bundle.putString("uuid", rosterAdapter.getData().get(position).getUuid());
                    bundle.putString("jump_type", "2");
                    ActivityForwardUtil.startActivity(AddCompanyActivity.class, bundle);
                } else {
                    if ("1".equals(rosterAdapter.getData().get(position).getIs_head_office())) {
                        bundle.putString("uuid", rosterAdapter.getData().get(position).getUuid());
                        bundle.putString("jump_type", "1");
                        ActivityForwardUtil.startActivity(AddCompanyActivity.class, bundle);
                    } else {
                        bundle.putString("uuid", rosterAdapter.getData().get(position).getUuid());
                        ActivityForwardUtil.startActivity(PersonnelDetailActivity.class, bundle);
                    }
                }
            }
        });
        //权限
        getMDatabind().ivLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getMDatabind().recyclerRow.getVisibility() == View.VISIBLE) {
                    getMDatabind().recyclerRow.setVisibility(View.GONE);
                    getMDatabind().ivLeft.setImageResource(R.mipmap.icon_base_hide);
                    MMKVHelper.putBoolean(ConstantMMVK.ROSTER_MENU_STATUS, false);
                } else {
                    getMDatabind().recyclerRow.setVisibility(View.VISIBLE);
                    getMDatabind().ivLeft.setImageResource(R.mipmap.icon_base_show);
                    MMKVHelper.putBoolean(ConstantMMVK.ROSTER_MENU_STATUS, true);
                }
            }
        });
        //增加
        getMDatabind().ivRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<BaseBottomListEntity> bottomListEntityList = new ArrayList<>();
                bottomListEntityList.add(new BaseBottomListEntity("添加项目成员", "保洁员、领班、项目主管"));
                bottomListEntityList.add(new BaseBottomListEntity("添加总部成员", "运营经理、管理员、人事"));
                CommonUtils.showBottomListCustomWith(getMActivity(), 20, "", bottomListEntityList, new OnDialogSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        Bundle bundle = new Bundle();
                        switch (position) {
                            case 0:
                                ActivityForwardUtil.startActivity(AddProjectActivity.class);
                                break;
                            case 1:
                                bundle.putString("jump_type", "" + position);
                                ActivityForwardUtil.startActivity(AddCompanyActivity.class, bundle);
                                break;
                        }
                    }
                });
            }
        });
        //分享
        getMDatabind().ivRightSide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] strings = {"导出花名册", "离职档案", "岗位管理", "用工规则"};

                CommonUtils.showBottomListWith(getActivity(), 20, "", strings, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        switch (position) {
                            case 0:
                                XXPermissions.with(getActivity())
                                        .permission(Permission.WRITE_EXTERNAL_STORAGE)
                                        .request(new OnPermissionCallback() {
                                            @Override
                                            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                                                if (allGranted) {
                                                    mViewModel.requestDownloadExcel("1", is_head_office, project_uuid);
                                                }
                                            }
                                        });
                                break;
                            case 1://离职档案
                                ActivityForwardUtil.startActivity(DepartActivity.class);
                                break;
                            case 2://岗位管理
                                FlutterBoost.instance().open(new FlutterBoostRouteOptions.Builder()
                                        .pageName("workPostPage")
                                        .arguments(new HashMap<>())
                                        .build());
                                break;
                            case 3://用工规则设置 跳转 flutter 先随便跳转 1 个
                                FlutterBoost.instance().open(new FlutterBoostRouteOptions.Builder()
                                        .pageName("workRulesPage")
                                        .arguments(new HashMap<>())
                                        .build());
                                break;
                        }
                    }
                });
            }
        });
    }


    @Override
    public void onRequestSuccess() {
        mViewModel.getRosterManager().observe(this, new Observer<RosterEntity>() {
            @Override
            public void onChanged(RosterEntity rosterEntity) {
                rowAdapter.setList(rosterEntity.getFilter_list());
                switch (requestType) {
                    case TYPE_INIT_DATA:
                        // 根据数据来决定要显示哪一个状态的View
                        if (CheckListDataUtil.checkInitData(rosterEntity.getList(), rosterAdapter, getMDatabind().list.refreshLayout)) {
                            rosterAdapter.setList(rosterEntity.getList());
                        }
                        break;
                    case TYPE_INIT_LOAD_MORE:
                        // 根据数据来决定要显示哪一个状态的View
                        if (CheckListDataUtil.checkLoadMoreData(rosterEntity.getList(), rosterAdapter, getMDatabind().list.refreshLayout)) {
                            rosterAdapter.addData(rosterEntity.getList());
                        }
                        break;
                }
            }
        });
        //监听请求内容
        mViewModel.getDownLoadEntity().observe(this, new Observer<BaseDownLoadEntity>() {
            @Override
            public void onChanged(BaseDownLoadEntity baseDownLoadEntity) {
                String fileName = App.appViewModelInstance.getUserInfo().getValue().getCompany().getCompany_name() + "_" + "花名册" + "_" + TimeUtils.date2String(TimeUtils.getNowDate(), "yyyy-MM-dd-hh-mm");
                DownLoadHelper.downloadFile(getActivity(), baseDownLoadEntity.getDownload_url(), null, fileName, true);
            }
        });
    }

    private void requestOne() {
        requestType = TYPE_INIT_DATA;
        page = 1;
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("page", "" + page);
        hashMap.put("size", "" + PAGE_SIZE);
        hashMap.put("status", "1");//状态 0全部 1在职 2离职
        hashMap.put("is_head_office", "" + is_head_office);//是否总部员工1是 2否 0不区分
        if (!TextUtils.isEmpty(project_uuid)) {
            hashMap.put("project_uuid", "" + project_uuid);
        }
        if (getMDatabind().etRosterSearch.getText().length() > 0) {
            hashMap.put("keyword", "" + getMDatabind().etRosterSearch.getText().toString());
        }
        if (filterData != null) {
            if (!TextUtils.isEmpty(filterData.getSex())) {
                hashMap.put("sex", "" + filterData.getSex());
            }
            if (!TextUtils.isEmpty(filterData.getMin_age())) {
                hashMap.put("min_age", "" + filterData.getMin_age());
            }
            if (!TextUtils.isEmpty(filterData.getMax_age())) {
                hashMap.put("max_age", "" + filterData.getMax_age());
            }
            if (!TextUtils.isEmpty(filterData.getStart_date())) {
                LogUtils.e("我是合约开始日期 + " + filterData.getStart_date());
                LogUtils.e("我是合约开始日期 + " + filterData.getStart_date().replace(" ~ ", "#"));
                hashMap.put("contract_start_date", "" + filterData.getStart_date().replace(" ~ ", "#"));
            }
            if (!TextUtils.isEmpty(filterData.getEnd_date())) {
                hashMap.put("contract_end_date", "" + filterData.getEnd_date().replace(" ~ ", "#"));
            }
            if (!TextUtils.isEmpty(filterData.getPic_status())) {
                hashMap.put("is_has_avatar", "" + filterData.getPic_status());
            }
            if (!TextUtils.isEmpty(filterData.getBank_status())) {
                hashMap.put("is_has_bank_card", "" + filterData.getBank_status());
            }
            if (!TextUtils.isEmpty(filterData.getHealth_status())) {
                hashMap.put("is_has_healthy_card", "" + filterData.getHealth_status());
            }
            if (!TextUtils.isEmpty(filterData.getRecode_check())) {
                hashMap.put("is_has_no_crime", "" + filterData.getRecode_check());
            }
        }
        mViewModel.getRosterList(hashMap);
    }

    private void requestMore() {
        requestType = TYPE_INIT_LOAD_MORE;
        page++;
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("page", "" + page);
        hashMap.put("size", "" + PAGE_SIZE);
        hashMap.put("status", "1");//状态 0全部 1在职 2离职
        hashMap.put("is_head_office", "" + is_head_office);//是否总部员工1是 2否 0不区分
        if (!TextUtils.isEmpty(project_uuid)) {
            hashMap.put("project_uuid", "" + project_uuid);
        }
        if (filterData != null) {
            if (!TextUtils.isEmpty(filterData.getSex())) {
                hashMap.put("sex", "" + filterData.getSex());
            }
            if (!TextUtils.isEmpty(filterData.getMin_age())) {
                hashMap.put("min_age", "" + filterData.getMin_age());
            }
            if (!TextUtils.isEmpty(filterData.getMax_age())) {
                hashMap.put("max_age", "" + filterData.getMax_age());
            }
            if (!TextUtils.isEmpty(filterData.getStart_date())) {
                hashMap.put("contract_start_date", "" + filterData.getStart_date());
            }
            if (!TextUtils.isEmpty(filterData.getEnd_date())) {
                hashMap.put("contract_end_date", "" + filterData.getEnd_date());
            }
            if (!TextUtils.isEmpty(filterData.getPic_status())) {
                hashMap.put("is_has_avatar", "" + filterData.getPic_status());
            }
            if (!TextUtils.isEmpty(filterData.getBank_status())) {
                hashMap.put("is_has_bank_card", "" + filterData.getBank_status());
            }
            if (!TextUtils.isEmpty(filterData.getHealth_status())) {
                hashMap.put("is_has_healthy_card", "" + filterData.getHealth_status());
            }
            if (!TextUtils.isEmpty(filterData.getRecode_check())) {
                hashMap.put("is_has_no_crime", "" + filterData.getRecode_check());
            }
        }
        mViewModel.getRosterList(hashMap);
    }
}
